package com.xxl.job.admin.controller.interceptor;

import cn.hutool.core.text.AntPathMatcher;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.core.util.FtlUtil;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.service.LoginService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

@Component
public class GlobalTransInterceptor implements RouterInterceptor {

    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Inject
    private LoginService loginService;
    @Inject("${pass.url:}")
    private String passUrl;
    @Inject("${admin.url:}")
    private String adminUrl;

    /**
     * 拦截处理（包围式拦截） //和过滤器的 doFilter 类似，且只对路由器范围内的处理有效
     */
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        String path = ctx.uri().getPath();
        boolean needLogin = true;
        boolean needAdminuser = false;
        for (String s : passUrl.split(",")) {
            if (s.contains("*")){
                boolean match = antPathMatcher.match(s, path);
                if (match) {
                    needLogin = false;
                    break;
                }
            }else if (s.equals(path)){
                needLogin = false;
                break;
            }
        }

        for (String s : adminUrl.split(",")) {
            if (s.contains("*")){
                boolean match = antPathMatcher.match(s, path);
                if (match) {
                    needAdminuser = true;
                    break;
                }
            }else if (s.equals(path)){
                needAdminuser = true;
                break;
            }
        }
        if (needLogin) {
            XxlJobUser loginUser = loginService.ifLogin(ctx);
            if (loginUser == null) {
                ctx.redirect("/toLogin");
                return;
            }
            ctx.attrSet(LoginService.LOGIN_IDENTITY_KEY, loginUser);
            if (needAdminuser && loginUser.getRole() != 1) {
                throw new RuntimeException(I18nUtil.getString("system_permission_limit"));
            }
        }
        chain.doIntercept(ctx, mainHandler);
    }

    /**
     * 提交结果（ render 执行前调用）//不要做太复杂的事情
     */
    @Override
    public Object postResult(Context ctx, Object result) throws Throwable {
        if (result instanceof ModelAndView mv) {
            mv.put("I18nUtil", FtlUtil.generateStaticModel(I18nUtil.class.getName()));
            XxlJobUser xxlJobUser = loginService.ifLogin(ctx);
            mv.put("loginUser", xxlJobUser);
        }
        return result;
    }
}